import React, { Component } from "react";
import { Provider } from "mobx-react";
import { BrowserRouter as Router, Route, /*Link,*/ Switch /*withRouter,Redirect*/ } from "react-router-dom";
import { hot } from "react-hot-loader";
import { ALogout, AGetUserInfo } from "../api";
import { HeaderSearch, NoticeIcon } from "ant-design-pro";
import {
Layout,
Menu,
Dropdown,
Avatar,
Icon,
Spin,
Modal
} from "antd";
import Login from "../components/login/Login";

import stores from "../store/index";
import routers from "../router/Router";
import { DDV } from "../public/debug";
import "../assets/less/index.less";
import "react-nprogress/nprogress.css";
import "../../src/api/mock";


class App extends Component {
    constructor(props) {
        super(props);

        this.state = {
            isLogin:      false,
            userData:     {
                avatar:      "",
                mobilePhone: "",
                nickname:    ""
            },
            loading:      !localStorage.getItem("access_token"),
            modalVisible: false,
            modalType:    true
        };
    }

    componentDidMount() {
        const localStorage_Uid = localStorage.getItem("uid");
        const localStorage_accessToken = localStorage.getItem("access_token");
        const localStorage_user = JSON.parse(localStorage.getItem("userData"));

        //uid 和 token 同时存在，说明已登录。
        if (localStorage_Uid && localStorage_accessToken) {
            this.setState({ isLogin: true });
            //判断本地是否存在 user 信息，有直接使用，没有重新请求
            if (!localStorage_user) {
                // 需要重新请求
                DDV("需要重新请求：", localStorage_user);
                this.handleUserInfo();

            } else {
                this.setState({
                    userData: localStorage_user,
                    loading: false,
                });
            }
            //关掉 Loading 动画
        } else {
            // 当前未登录，回调 App.js 中的 setLoading 方法，关掉 loading 动画
            this.setState({
                isLogin: false,
                loading: false
            });

        }
    }

    handleUserInfo = async () => {
        return await AGetUserInfo().then(async (obj) => {
            DDV("请求时间-：", obj);
            await localStorage.setItem("userData", JSON.stringify(obj.data.data));
            // this.state.userData = obj.data.data;
            await this.setState({
                userData: obj.data.data,
                loading:  false,
                isLogin: true,
            });
        });
    };

    handleToolsMenuClick = ({ key }) => {
        if (key === "logout") {
            ALogout();
            this.setState({
                isLogin: false
            });
        }
    };

    handleModal = (type) => {
        DDV("handleModal: ", type);
        this.setState({ modalVisible: true, modalType: type });
    };
    handleModalType = () => {
        this.setState({
            modalType : !this.state.modalType
        })
    };

    handleOk = () => {
        this.setState({ modalVisible: false });
    };
    handleCancel = () => {
        this.setState({ modalVisible: false });
    };

    render() {

        const { Header, Content, Footer } = Layout;

        const menu = (
            <Menu className="yi-header-tools-menu" selectedKeys={[]} onClick={this.handleToolsMenuClick}>
                <Menu.Item key="userCenter">
                    <Icon type="user" />
                    个人中心
                </Menu.Item>
                <Menu.Item key="userinfo">
                    <Icon type="setting" />
                    设置
                </Menu.Item>
                <Menu.Divider />
                <Menu.Item key="logout">
                    <Icon type="logout" />
                    退出
                </Menu.Item>
            </Menu>
        );
        const modalLogin = (
            <Login handleModalType={this.handleModalType} handleUserInfo={this.handleUserInfo} handleCancel={this.handleCancel}/>
        );
        const modalRegister = (
            <p>register</p>
        );

        return (
            <Provider {...stores} >
                <Spin
                    size="large"
                    spinning={this.state.loading}
                    wrapperClassName="yi-test-spin"
                >
                    <div className='yi'>
                        <Router>
                            <main>
                                <div className='yi'>
                                    <Layout className="layout">
                                        <Header className='yi-header'>
                                            <div className="yi-logo">鱼音</div>
                                            <Menu
                                                theme="light"
                                                mode="horizontal"
                                                defaultSelectedKeys={["1"]}
                                                className="yi-menu"
                                            >
                                                <Menu.Item key="1">nav 1</Menu.Item>
                                                <Menu.Item key="2">nav 2</Menu.Item>
                                                <Menu.Item key="3">nav 3</Menu.Item>
                                            </Menu>
                                            <div className="yi-search">
                                                <HeaderSearch
                                                    open={true}
                                                    defaultOpen={true}
                                                    placeholder="站内搜索"
                                                    dataSource={["搜索提示一", "搜索提示二", "搜索提示三"]}
                                                    onSearch={(value) => {
                                                        console.log("input", value); // eslint-disable-line
                                                    }}
                                                    onPressEnter={(value) => {
                                                        console.log("enter", value); // eslint-disable-line
                                                    }}
                                                />
                                            </div>
                                            {
                                                this.state.isLogin ?
                                                    (
                                                        <div className="yi-header-tools">
                                                            <NoticeIcon
                                                                className="yi-header-tools-notice action"
                                                                count={5}
                                                                popupAlign={{ offset: [20, -16] }}
                                                            >
                                                                <NoticeIcon.Tab
                                                                    title="通知"
                                                                    emptyText="你已查看所有通知"
                                                                    emptyImage="https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg"
                                                                />
                                                            </NoticeIcon>

                                                            <Dropdown overlay={menu}>
                                            <span className="yi-header-tools-avatar action">
                                              <Avatar
                                                  className="yi-header-tools-avatar-img"
                                                  alt="avatar"
                                                  src={this.state.userData.avatar}
                                              />
                                              <span
                                                  className="yi-header-tools-avatar-text">{this.state.userData.nickname}</span>
                                            </span>
                                                            </Dropdown>
                                                        </div>
                                                    ) : (
                                                        <div className="yi-header-tools-login">
                                                            <span className="link" onClick={() => this.handleModal(true)}>登录</span>
                                                            <span>/</span>
                                                            <span className="link" onClick={() => this.handleModal(false)}>注册</span>
                                                        </div>
                                                    )
                                            }

                                        </Header>
                                        <Content style={{ width: 1120, margin: "0 auto", padding: "0 20px" }}>
                                            <Modal
                                                visible={this.state.modalVisible}
                                                onCancel={this.handleCancel}
                                                footer={null}
                                                title={this.state.modalType ? "登录" : "注册"}
                                                width={400}
                                                >
                                                {this.state.modalType ? modalLogin : modalRegister}
                                            </Modal>
                                            <Switch>
                                                {
                                                    routers.map((route, index) => {
                                                        const Component = route.render;
                                                        return (
                                                            <Route
                                                                key={index}
                                                                path={route.path}
                                                                exact={route.exact}
                                                                render={props => (
                                                                    < Component {...props}
                                                                                setLoading={this.setLoading} />
                                                                )}
                                                            />
                                                        );
                                                    })
                                                }
                                            </Switch>

                                        </Content>
                                        <Footer style={{ textAlign: "center" }}>
                                            鱼音 ©2018 Created by BoooxTechnologies
                                        </Footer>
                                    </Layout>
                                </div>

                            </main>
                        </Router>
                    </div>
                </Spin>
            </Provider>
        );
    }
}

export default hot(module)(App);
